const express = require('express')
const router = express.Router()
const { count, list, detail, insert, update, remove } = require('@/dao/ArticleDao')

const { detail: categoryDetail } = require('@/dao/CategoryDao')
const { detail: tagDetail } = require('@/dao/TagDao')

router.get('/', async (req, res) => {
  const total = await count()
  const data = await list(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult([], _code.OPE, '请求失败，请稍后再试')
  const result = {
    total: total[0].count,
    rows: data
  }
  res.sendResult(result, _code.GDS, '请求成功')
})

router.get('/detail', async (req, res) => {
  let result = null
  const data = await detail(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult([], _code.OPE, '请求失败，请稍后再试')
  if (data.length === 0) return res.sendResult(null, _code.GDE, '未找到该文章')
  // 为文章详情补充分类名称
  if (data[0] && data[0].category) {
    const res = await categoryDetail({ query: { id: data[0].category } })
    result = {
      ...data[0],
      category_name: res[0].title
    }
  }
  // 为文章详情补充标签名称
  if (data[0] && data[0].tags) {
    const tagIds = data[0].tags.split(',')
    const tagList = []
    for (let i = 0; i < tagIds.length; i++) {
      const ele = tagIds[i];
      const res = await tagDetail({ query: { id: ele } })
      tagList.push(res[0])
    }
    result = {
      ...result,
      tagList
    }
  }
  res.sendResult(result || data[0], _code.GDS, '请求成功')
})

router.post('/insert', async (req, res) => {
  const data = await insert(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, '操作失败，请稍后再试')
  res.sendResult(data.insertId, _code.OPS, '添加成功')
})

router.put('/update', async (req, res) => {
  const data = await update(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, '操作失败，请稍后再试')
  res.sendResult(data, _code.OPS, '修改成功')
})

router.delete('/remove', async (req, res) => {
  const data = await remove(req)
  if (data.code && data.code.indexOf('ER') !== -1) return res.sendResult(null, _code.OPE, '删除失败，请稍后再试')
  res.sendResult(req.body.id, _code.OPS, '删除成功')
})

module.exports = router;
